package com.itlaobing.spring.ioc.scope;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/loong/*")
public class LoongServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html ; charset=UTF-8");

        PrintWriter out = response.getWriter();

        ServletContext application = this.getServletContext();

        // 从 Web 环境中 获取 Spring 的 IoC 容器 ( 即从 ServletContext 中获取 IoC 容器 )
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(application);

        Loong first = context.getBean("first" ,Loong.class);

        out.println("<p>");
        out.println( first);
        out.println("<p>");

        Loong second = context.getBean("second" ,Loong.class);

        out.println("<p>");
        out.println( second );
        out.println("<p>");
    }
}
